package br.com.wryel.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.ModelAndView;

import br.com.wryel.controller.form.UsuarioLoginForm;
import br.com.wryel.controller.form.validator.UsuarioLoginFormValidation;
import br.com.wryel.model.UsuarioModel;
import br.com.wryel.model.entity.Usuario;

@Scope(WebApplicationContext.SCOPE_APPLICATION)
@Controller
@RequestMapping("/usuario")
public class UsuarioController extends EntityController<Usuario, UsuarioModel> {
	
	@Autowired
	private UsuarioLoginFormValidation usuarioLoginFormValidation;
	
	public UsuarioController() {
		super(UsuarioModel.class);
	}
		
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public ModelAndView login() {
		ModelAndView modelAndView = new ModelAndView("view/usuario/login");
		modelAndView.addObject("usuarioLoginForm", new UsuarioLoginForm());
		return modelAndView;
	}
	
	@RequestMapping(value = "/logout", method = RequestMethod.GET)
	public String logout(HttpSession httpSession) {
		if (httpSession != null) {
			httpSession.invalidate();
		}
		return prepareForRedirect("/index.html");
	}
	@RequestMapping(value = "/loginValidate", method = RequestMethod.POST)

	public ModelAndView loginValidate(@ModelAttribute UsuarioLoginForm usuarioLoginForm, BindingResult bindingResult, HttpServletRequest httpServletRequest) {
		usuarioLoginFormValidation.validate(usuarioLoginForm, bindingResult);
		ModelAndView modelAndView = new ModelAndView();
		if (bindingResult.hasErrors()) {
			modelAndView.setViewName("view/usuario/login");
			modelAndView.addObject("usuarioLoginForm", usuarioLoginForm);
			return modelAndView;
		}
		HttpSession httpSession = httpServletRequest.getSession();
		httpSession.setAttribute(SessionParam.USER, usuarioLoginForm.getUsuario());
		modelAndView.setViewName(prepareForRedirect("/index.html"));
		return modelAndView;
	}

	public UsuarioLoginFormValidation getUsuarioLoginFormValidation() {
		return usuarioLoginFormValidation;
	}

	public void setUsuarioLoginFormValidation(UsuarioLoginFormValidation usuarioLoginFormValidation) {
		this.usuarioLoginFormValidation = usuarioLoginFormValidation;
	}
}